package com.ljt.yupictureddd.shared.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.ljt.yupictureddd.shared.manager.websocket.PictureEditHandler;
import com.ljt.yupictureddd.shared.manager.websocket.model.PictureEditMessageTypeEnums;
import com.ljt.yupictureddd.shared.manager.websocket.model.PictureEditRequestMessage;
import com.ljt.yupictureddd.shared.manager.websocket.model.PictureEditResponseMessage;
import com.ljt.yupictureddd.domain.user.entity.User;
import com.ljt.yupictureddd.application.service.UserApplicationService;
import com.lmax.disruptor.WorkHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * 图片编辑时间处理器（消费者）
 */
@Component
@RequiredArgsConstructor
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {
    private final UserApplicationService userApplicationService;
    private final PictureEditHandler pictureEditHandler;


    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        PictureEditRequestMessage pictureEditRequestMessage = pictureEditEvent.getPictureEditRequestMessage();
        WebSocketSession session = pictureEditEvent.getSession();
        User user = pictureEditEvent.getUser();
        Long pictureId = pictureEditEvent.getPictureId();


        // 获取消息内容,讲JSON转换为PictureEditRequestMessage
        PictureEditMessageTypeEnums picTypeEnums = PictureEditMessageTypeEnums.getEnumByValue(pictureEditRequestMessage.getType());

        // 对前端请求进行处理
        switch (picTypeEnums) {
            case ENTER_EDIT:
                pictureEditHandler.handlerEnterEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handlerExitEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handlerEditActionMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            default:
                // 这个写不写无所谓,其他消息类型,暂时不处理
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnums.ERROR.getValue());
                pictureEditResponseMessage.setMessage("消息类型错误");
                pictureEditResponseMessage.setUser(userApplicationService.getUserVO(user));
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditRequestMessage)));
                break;
        }
    }
}
